package com.fujimana.rockincat.restree.phase;

import java.util.Iterator;
import java.util.Map;

import com.fujimana.rockincat.restree.context.Context;
import com.fujimana.rockincat.restree.proxy.MethodMetaData;
import com.fujimana.rockincat.restree.proxy.ResourceProxy;
import com.fujimana.rockincat.restree.service.Response;

public class InvokeApplicationPahse implements Phase {
	
	@SuppressWarnings("unchecked")
	@Override
	public void execute(Map<String, Object> context) {
		Map<String, ResourceProxy> proxyLinkMap = (Map<String, ResourceProxy>) context.get("resourceTree");
		Context rstCtx = (Context) context.get(Context.class.getName());
		ResourceProxy proxy = (ResourceProxy) context.get(ResourceProxy.class.getName());
		MethodMetaData metaData = (MethodMetaData) context.get(MethodMetaData.class.getName());
		
		Iterator<String> it = proxyLinkMap.keySet().iterator();
		
		while(it.hasNext()) {
			String key = it.next();
			ResourceProxy p = proxyLinkMap.get(key);
			
			rstCtx.set("resource", key);
			p.handle(rstCtx);
		}
		
		Object ret = proxy.call(metaData.getAnnotatin(), rstCtx);
		
		context.put("return", ret);
	}

	@Override
	public String getId() {
		return InvokeApplicationPahse.class.getSimpleName();
	}

	@Override
	public boolean isChain() {
		return Response.getResponse().isRedirect() == false;
	}
}
